package org.openwp3x.iclazz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

public class RestClient {

	private final ArrayList<NameValuePair> params;
	private final ArrayList<NameValuePair> headers;

	private final String url;

	private int responseCode;
	private String message;

	private String response;

	public String getResponse() {
		return this.response;
	}

	public String getErrorMessage() {
		return this.message;
	}

	public Integer getResponseCode() {
		return this.responseCode;
	}

	public RestClient(final String url) {
		this.url = url;
		this.params = new ArrayList<NameValuePair>();
		this.headers = new ArrayList<NameValuePair>();
	}

	public void AddParam(final String name, final String value) {
		this.params.add(new BasicNameValuePair(name, value));
	}

	public void AddHeader(final String name, final String value) {
		this.headers.add(new BasicNameValuePair(name, value));
	}

	public void Execute(final RequestMethod method) throws Exception {
		switch (method) {
		case GET: {
			// add parameters
			String combinedParams = "";
			if (!this.params.isEmpty()) {
				combinedParams += "?";
				for (NameValuePair p : this.params) {
					String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue());
					if (combinedParams.length() > 1) {
						combinedParams += "&" + paramString;
					} else {
						combinedParams += paramString;
					}
				}
			}

			HttpGet request = new HttpGet(this.url + combinedParams);

			// add headers
			for (NameValuePair h : this.headers) {
				request.addHeader(h.getName(), h.getValue());
			}

			executeRequest(request, this.url);
			break;
		}
		case POST: {
			HttpPost request = new HttpPost(this.url);

			// add headers
			for (NameValuePair h : this.headers) {
				request.addHeader(h.getName(), h.getValue());
			}

			if (!this.params.isEmpty()) {
				request.setEntity(new UrlEncodedFormEntity(this.params, HTTP.UTF_8));
			}

			executeRequest(request, this.url);
			break;
		}
		}
	}

	private void executeRequest(final HttpUriRequest request, final String url) {
		HttpClient client = new DefaultHttpClient();

		HttpResponse httpResponse;

		try {
			HttpConnectionParams.setConnectionTimeout(request.getParams(), 500);

			httpResponse = client.execute(request);
			this.responseCode = httpResponse.getStatusLine().getStatusCode();
			this.message = httpResponse.getStatusLine().getReasonPhrase();

			HttpEntity entity = httpResponse.getEntity();

			if (entity != null) {

				InputStream instream = entity.getContent();
				this.response = RestClient.convertStreamToString(instream);

				// Closing the input stream will trigger connection release
				instream.close();
			}

		} catch (ClientProtocolException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
		} catch (IOException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
		}
	}

	private static String convertStreamToString(final InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while (( line = reader.readLine() ) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}